package com.dl.utils;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author DL
 * @create 2021-05-27 17:25
 */
@Component
public class EmailUtils {

    @Resource
    private JavaMailSenderImpl mailSender;

    @Resource
    private TemplateEngine templateEngine;

    /**
     * 发送邮件测试方法
     */
    public void sendMail(String subject, String emailTO, String username, String password) throws MessagingException {
/*        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.qq.com");
        mailSender.setPort(465);
        mailSender.setUsername("2458697735@qq.com");
        mailSender.setPassword("rsrqmjvuneyaebfj");
        mailSender.setProtocol("smtps");
        Properties properties = new Properties();
        properties.put("mail.smtp.auth",true);
        properties.put("smtp.ssl.enable",true);
        properties.put("smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.ssl.enable",true);
        mailSender.setJavaMailProperties(properties);*/

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom("2458697735@qq.com"); //发件人邮箱
        messageHelper.setTo(emailTO);//收件人邮箱
        messageHelper.setSubject(subject);//邮件主题

        Context context = new Context();
        context.setVariable("email",emailTO);
        context.setVariable("username",username);
        context.setVariable("password",password);

        //获取thymeleaf模版
        String content = templateEngine.process("/commons/email",context);

        messageHelper.setText(content,true);
        mailSender.send(mimeMessage);
    }

}
